#include "httpauditor.h"


httpauditor::httpauditor(void):_Log(0),_httpsession(0),_quitflag(0),_ringfifo(0)
{
}


httpauditor::~httpauditor(void)
{
	destroy();
}
int httpauditor::create(){
	if(_httpsession==0){
		_httpsession=new httpSession;
		if(_httpsession){
			if(_httpsession->init()==0){
				return 0;
			}
			else{
				if(_Log){
					_Log->message("auditor: session init  failed.\n");
				}
			}
		}
			
	}
	return -1;
}
int httpauditor::destroy(){
	if(_httpsession){
		delete _httpsession;
		_httpsession=0;
		return 0;
	}
	return -1;
}
int httpauditor::load_config(){
	return 0;
}
int httpauditor::svc(){
	if(_Log){
		_Log->message("auditor: task begin...\n");
	}

	tcp_connection_info tci;
	int size=0;
	int ret=0;
	while(!_quitflag){

		if(_ringfifo){
			ret=_ringfifo->pop_front(tci);
			if(ret==0){
				process_data(&tci);
			}
			else if(ret==1){
				if(_Log){
					_Log->message("auditor: ringfifo disabled. \n");
				}
				break;
			}
			//printf("ringfifo element num: %d \n",_ringfifo->get_element_size());
		}
		Sleep(10);
	}
	if(_Log){
		_Log->message("auditor: task done. \n");
	}
	return 0;
}
int httpauditor::process_data(tcp_connection_info* tci){
	if(!tci||!_httpsession){
		return -1;
	}
	Ntuple4  key;
	key.saddr=tci->saddr;
	key.daddr=tci->daddr;
	key.source=tci->source;
	key.dest=tci->dest;
	if(tci->state==tcp_conn_just_est){
		_httpsession->create_session(key);
		//printf("conn est\n");
		return 0;
	}
	if(tci->state==tcp_conn_rst){
		_httpsession->destroy_session(key);
		//printf("conn rst\n");
		return 0;
	}
	if(tci->state==tcp_conn_close){
		_httpsession->destroy_session(key);
		//printf("conn close\n");
		return 0;
	}
	if(tci->state==tcp_conn_data){
		if(tci->direct==fromserver){
			_httpsession->update_session(key,tci->data,tci->datalen,fromserver);
			//printf("client recv: %s \n",tci->data);
		}
		if(tci->direct==fromclient){
			_httpsession->update_session(key,tci->data,tci->datalen,fromclient);
			//printf("server recv: %s \n",tci->data);
		}
	}
	return 0;
}

void httpauditor::register_callback(SESSION_CALLBACK p){
	if(_httpsession){
		_httpsession->register_session_callback(p);
	}
}
void httpauditor::register_interaction_callback(INTERACTION_CALLBACK p){
	if(_httpsession){
		_httpsession->register_interaction_callback(p);
	}
}
int httpauditor::reset(){
	_httpsession->clear();
	return 0;
}